﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SES.CMS.DO;
using SES.CMS.BL;
using SES.CMS.AdminCP;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Net.Configuration;
using System.Configuration;

namespace SES.CMS
{
    public partial class order : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["CustomerID"] != null)
                {
                    LoadDetail();
                    LoadForm();
                }
                else
                {
                    InfoDetail.Visible = false;
                    lbDangnhap.CssClass = "red";
                }

                if (Session["shop"] == null)
                {
                    Session["shop"] = new MyShopCart();
                }
                //AddItem();
                ShowData();
            }


            txtUsername.Attributes.Add("onkeypress", "doClick('" + btnLogin.ClientID + "',event)");
            txtPass.Attributes.Add("onkeypress", "doClick('" + btnLogin.ClientID + "',event)");
            //SEO
            Page.Title = "Thanh toán đơn hàng | " + Ultility.WebTitle();

            sysConfigDO objConfig = new sysConfigDO();
            objConfig.ConfigID = 2;

            objConfig = new sysConfigBL().Select(objConfig);


            HtmlMeta metaKey = new HtmlMeta();
            metaKey.Name = "keywords";
            metaKey.Content = objConfig.ConfigValue;
            Page.Header.Controls.Add(metaKey);


            objConfig.ConfigID = 3;
            objConfig = new sysConfigBL().Select(objConfig);
            HtmlMeta metaDesc = new HtmlMeta();
            metaDesc.Name = "description";
            metaDesc.Content = objConfig.ConfigValue;
            Page.Header.Controls.Add(metaDesc);
        }

        private void ShowData()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Id");
            table.Columns.Add("Name");
            table.Columns.Add("Cost");
            table.Columns.Add("Image");
            table.Columns.Add("Quantity");
            table.Columns.Add("TotalCost");
            if (Session["shop"] != null)
            {
                foreach (var item in ((MyShopCart)Session["shop"]).ListProduct)
                {

                    DataRow row = table.NewRow();
                    row["Id"] = item.Id;
                    row["Name"] = item.Name;
                    if (item.Cost == null)
                    {
                        String.Format("{0:0,0}", 0);
                    }
                    else
                    {
                        row["Cost"] = String.Format("{0:0,0}", item.Cost);
                    }
                    row["Image"] = item.Image;
                    row["Quantity"] = item.Quantity;
                    row["TotalCost"] = String.Format("{0:0,0}", item.Quantity * item.Cost);

                    table.Rows.Add(row);
                }

                GridView1.DataSource = table;
                GridView1.DataBind();
            }


            if (Session["shop"] != null)
            {
                decimal totalCost = ((MyShopCart)Session["shop"]).GetTotalCost();
                ltTongTien.Text = String.Format("{0:0,0}", totalCost) + " VNĐ";

                string longCost = String.Format("{0:0}", totalCost);
                ClsDocTien cls = new ClsDocTien();
                //ltTongTienChu.Text = cls.DocTien(Convert.ToInt64(longCost), " đồng");
            }
        }

        void LoadForm()
        {
            cmsCustomerDO itemDO = new cmsCustomerDO();
            int userID = Convert.ToInt32(Session["CustomerID"]);
            itemDO.Id = userID;
            itemDO = new cmsCustomerBL().Select(itemDO);

            txtName.Text = itemDO.FullName;
            txtAddress.Text = itemDO.Address;
            txtEmail.Text = itemDO.Email;
            txtNgayNhan.Text = DateTime.Now.ToString("dd/MM/yyyy");
            txtPhone.Text = itemDO.Phone;
        }

        void LoadDetail()
        {
            loginUser.Visible = false;
            InfoDetail.Visible = true;
            lbThongtin.CssClass = "red";
        }
        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            LoadDetail();
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string sPass = SES.CMS.AdminCP.Functions.EncryptMd5(txtPass.Text.Trim());
            DataTable dtUser = new cmsCustomerBL().SelectLogin(txtUsername.Text.Trim(), sPass);
            if (dtUser.Rows.Count > 0)
            {
                Session["FullName"] = dtUser.Rows[0]["FullName"].ToString();
                Session["CustomerID"] = dtUser.Rows[0]["ID"].ToString();

                Response.Redirect("/thanh-toan/");
                LoadDetail();
            }
            else
            {
                SES.CMS.AdminCP.Functions.Alert("Sai tên đăng nhập");
            }
        }
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            Response.Redirect("/dang-ky/");
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
           
                AddShopcart();
                SendMail();
                Session["shop"] = null;
                InfoDetail.Visible = false;
                loginUser.Visible = false;
                success.Visible = true;
                lbSucsess.CssClass = "red";
                lbThongtin.CssClass = "";
        }
        private void Reset()
        {
            txtPhone.Text = "";
            txtName.Text = "";
            txtEmail.Text = "";
            txtAddress.Text = "";
            txtNgayNhan.Text = "";
        }
        public static String Address
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.UserName;
            }
        }
        public static String Pass
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.Password;
            }
        }
        void SendMail()
        {
            DateTime now = DateTime.Now;
            string date = now.Day + " - " + now.Month + " - " + now.Year;

            MyShopCart myShop = (MyShopCart)Session["shop"];
            string totalCost = String.Format("{0:0,0}", myShop.GetTotalCost());

            string content = "<div style='margin-top:10px'>";
            content += "<fieldset>";
            content += "<legend>Thông tin đặt hàng</legend>";
            content += " <table width='100%' border='1' cellpadding='3' cellspacing='0' style='border-collapse:collapse'>";
            content += "<tbody><tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Thông tin khách hàng </td></tr>";
            content += "<tr><td style='width:100px'>Họ tên : </td><td>" + txtName.Text + "</td></tr>";
            content += "<tr><td>Địa chỉ : </td><td>" + txtAddress.Text + "</td></tr>";
            content += "<tr><td>Điện thoại : </td><td>" + txtPhone.Text + "</td></tr> ";
            content += "<tr><td>Email : </td><td>" + txtEmail.Text + "</td></tr>";
            //content += "<tr><td>Ghi chú : </td><td>" + txtNotes.Text + "</td></tr>";
            content += "<tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Thông tin sản phẩm đặt hàng </td></tr>";
            int count_item = 1;
            foreach (var item in myShop.ListProduct)
            {
                content += "<tr><td style='width:100px'>Sản phẩm " + count_item + "</td><td>" + item.Name + " - Mã : " + item.Id + " - Số lượng : " + item.Quantity + " - Giá : " + String.Format("{0:0,0}", item.Cost) + "</td></tr>";
                count_item++;
            }
            content += "<tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Tổng giá trị : " + totalCost + "</td></tr>";
            content += "</table>";
            content += "<p>Ngày gửi : " + date + "</p></fieldset></div>";
            Myfunction.SendMail(Address, Pass, "Đơn đặt hàng - TopBike", txtEmail.Text.Trim(), "Đơn đặt hàng ngày " + now.ToString(), content);
        }
        void AddShopcart()
        {
            if (txtName.Text == "")
            {
                Myfunction.ThongBao(ltThongBao, "Nhập họ tên ! ");
                txtName.Focus();
                return;
            }
            if (txtEmail.Text == "")
            {
                Myfunction.ThongBao(ltThongBao, "Nhập họ tên ! ");
                txtEmail.Focus();
                return;
            }
            if (txtAddress.Text == "")
            {
                Myfunction.ThongBao(ltThongBao, "Nhập địa chỉ giao hàng! ");
                txtAddress.Focus();
                return;
            }
            if (txtNgayNhan.Text == "")
            {
                Myfunction.ThongBao(ltThongBao, "Chọn ngày giao hàng! ");
                txtNgayNhan.Focus();
                return;
            }
            if (txtAddress.Text == "")
            {
                Myfunction.ThongBao(ltThongBao, "Nhập địa chỉ nhận hàng! ");
                txtNgayNhan.Focus();
                return;
            }
            if (!Myfunction.isEmailValid(txtEmail.Text))
            {
                Myfunction.ThongBao(ltThongBao, "Nhập email không hợp lệ ! ");
                txtEmail.Focus();
                return;
            }

            cmsCustomerBL data = new cmsCustomerBL();
            cmsCustomerDO itemCustomerDO = new cmsCustomerDO();
            cmsOrdersDO itemOrderDO = new cmsOrdersDO();
            cmsOrdersBL dataOrder = new cmsOrdersBL();
            int customerId = 0;
            if (Session["CustomerID"] != null)
            {
                //Customer
                customerId = Convert.ToInt32(Session["CustomerID"]);
                itemCustomerDO.Id = customerId;
                itemCustomerDO = new cmsCustomerBL().Select(itemCustomerDO);
                itemCustomerDO.Address = itemCustomerDO.Address;
                itemCustomerDO.Brithday = itemCustomerDO.Brithday;
                itemCustomerDO.Email = txtEmail.Text.Trim();
                itemCustomerDO.FullName = txtName.Text.Trim();
                itemCustomerDO.IsEnable = itemCustomerDO.IsEnable;
                itemCustomerDO.IsVangLai = itemCustomerDO.IsVangLai;
                itemCustomerDO.Password = itemCustomerDO.Password;
                itemCustomerDO.Phone = itemCustomerDO.Phone;
                itemCustomerDO.RegisterDay = itemCustomerDO.RegisterDay;
                itemCustomerDO.Sex = itemCustomerDO.Sex;
                itemCustomerDO.UserName = itemCustomerDO.UserName;
                data.Update(itemCustomerDO);
            }
            else
            {
                //Customer
                itemCustomerDO.Address = txtAddress.Text;
                itemCustomerDO.Brithday = Convert.ToDateTime("1/1/1900");
                itemCustomerDO.Email = txtEmail.Text.Trim();
                itemCustomerDO.FullName = txtName.Text.Trim();
                itemCustomerDO.IsEnable = false;
                itemCustomerDO.IsVangLai = true;
                itemCustomerDO.Password = "";
                itemCustomerDO.Phone = txtPhone.Text;
                itemCustomerDO.RegisterDay = Convert.ToDateTime("1/1/1900");
                //itemCustomerDO.Sex = ;
                itemCustomerDO.UserName = "";
                customerId = data.Insert(itemCustomerDO);
            }
            //Order
            itemOrderDO.CreateDate = DateTime.Now;
            itemOrderDO.Address = txtAddress.Text.Trim();
            itemOrderDO.CustomerId = customerId;
            itemOrderDO.DateOfStart = DateTime.Now;
            itemOrderDO.DateOfFisnish = Myfunction.ReturnValidateDateTime(txtNgayNhan.Text);
            itemOrderDO.IsEnable = false;
            itemOrderDO.IsView = false;
            itemOrderDO.Phone = txtPhone.Text.Trim();
            itemOrderDO.Status = false;

            int idOrder = dataOrder.Insert(itemOrderDO);

            //OrderDetail
            cmsOrderDetailsDO itemOrderDetailDO = new cmsOrderDetailsDO();
            cmsOrderDetailsBL dataOrderDetail = new cmsOrderDetailsBL();

            foreach (var item in ((MyShopCart)Session["shop"]).ListProduct)
            {
                itemOrderDetailDO.Qty = item.Quantity;
                itemOrderDetailDO.ProductId = item.Id;
                itemOrderDetailDO.Price = int.Parse(item.Cost.ToString().Replace(",", ""));
                itemOrderDetailDO.OrderId = idOrder;
                dataOrderDetail.Insert(itemOrderDetailDO);
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/");
        }
    }
}